// pages/category/category.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        current: 0,
        page: 1,
        total: 2,
        loading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.catScrollLeft = 0
        this.loadCategory()
    },
    loadCategory() {

        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.get("index/category", {
            showMsg: true
        }).then(res => {
            this.setData({
                category: res.data.categories
            })
            this.loadGoods()
            wx.setNavigationBarTitle({
                title: wx.getStorageSync('store'),
            })
            wx.hideLoading()
        })
    },

    loadGoods() {
        let { page = 1, total = 2, loading = false, goods = [] } = this.data.category[this.data.current]
        if (page > total || loading) {
            return
        }
        wx.showLoading({
            title: '加载中...',
        })
        this.setData({
            [`category[${this.data.current}].loading`]: true
        })
        getApp().http.post("goods/list?page=" + page, {
            data: {
                category_id: this.data.category[this.data.current].id,
            },
            showMsg: true,
        }).then(res => {
            page++
            total = res.data.total
            goods.push(...res.data.goods_list)
            loading = false
            this.setData({
                [`category[${this.data.current}]`]: Object.assign(this.data.category[this.data.current], {
                    page, total, goods, loading
                })
            })
            wx.hideLoading()
        })
    },
    onCatScroll(e) {
        this.catScrollLeft = e.detail.scrollTop
        console.log(this.catScrollLeft)
    },
    catClick(evt) {
        const { index } = evt.currentTarget.dataset
        this.setData({
            current: index
        })
        this.loadGoods()
        // if (wx.createSelectorQuery) {
        //缓动，待基础版本稳定了再开
        // this.setData({
        //     hasQuery: true
        // })
        // const query = wx.createSelectorQuery()
        // query.select("#cat" + index).boundingClientRect()
        // query.select("#cat").boundingClientRect()
        // query.exec(res => {
        //     console.log(res[0])
        //     let scrollX = res[0].scrollLeft
        //     this.setData({
        //         tag: {
        //             top: res[0].top + this.catScrollLeft,
        //             height: res[0].height,
        //         },
        //         scrollX
        //     })
        // })
        // }
    }
})